package com.pay.sdk.zftzl.usage;

import android.content.Context;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.pay.sdk.zftzl.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import sdk.pay.model.TokenParam;
import sdk.pay.utils.PayAESUtil;


/**
 * Created by lj on 2017/6/28 0028.
 */

public class PayParameter {
    public static final String TAG = "junfutong";
    private static final String API_PAYPARAM = "https://api.z.jtpay.com/services/getServerDemo";
    //此处KEY_AES与VECTOR_AES为自定义与商户注册无关
    private static final String KEY_AES = "1f3ebc7yhambcqq8n21sq6l0415lvuux";
    private static final String VECTOR_AES = "8l1k0bkv23xbp0xz";
    private static final String LIST_PARAM = "2";
    private static final String PAY_PARAM = "1";
    public final static long TIME_OUT = 30L;
    public PayParametercCallback mPayParametercCallback;
    public PaySignCallback mPaySignCallback;
    private static OkHttpClient mOkHttpClient;
    private static final TokenParam mTokenParam = new TokenParam();

    static {
        mOkHttpClient = new OkHttpClient.Builder().connectTimeout(TIME_OUT, TimeUnit.SECONDS).readTimeout(TIME_OUT, TimeUnit.SECONDS).build();
    }

    public PayParameter() {
    }

    public void getPayParameter(final Context context, String goodsPrice, String product) {
        JSONObject object = new JSONObject();
        try {
            object.put("money", goodsPrice);
            object.put("typeCode", LIST_PARAM);
            object.put("productName", product);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d(TAG, "Merchants configuration errors" + e.toString());
            if (mPayParametercCallback != null) {
                mPayParametercCallback.failureParameter(context.getString(R.string.merchants_configuration_errors));
            }
        }
        String url = getUrl(object.toString(), API_PAYPARAM);
        Log.d(TAG, "list configuration  url = " + url);
        getCall(TAG, url, new PayCallback() {
            @Override
            public void onFailure() {
                if (null != mPayParametercCallback) {
                    mPayParametercCallback.failureParameter(context.getString(R.string.merchants_configuration_errors));
                }
                Log.d(TAG, "Merchants configuration errors");
            }

            @Override
            public void onSuccess(Call call, Response response) throws IOException {
                if (null != response.body().toString()) {
                    String result = response.body().string();
                    if (response.isSuccessful()) {
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String flag = jsonObject.getString("flag");
                            if ("1".equals(flag)) {
                                String msg = jsonObject.getString("msg");
                                String str = getDecrypt(msg);
                                if (!TextUtils.isEmpty(str)) {
                                    JSONObject jsonObject1 = new JSONObject(str);
                                    mTokenParam.setP2_orderNumber(jsonObject1.getString("orderNumber"));
                                    mTokenParam.setP3_money(jsonObject1.getString("money"));
                                    mTokenParam.setP6_orderTime(jsonObject1.getString("ordertime"));
                                    mTokenParam.setP1_appid(jsonObject1.getString("appid"));
                                    mTokenParam.setKey(jsonObject1.getString("appSdkKey"));
                                    mTokenParam.setVector(jsonObject1.getString("appAesXl"));
                                    mTokenParam.setP8_sign(jsonObject1.getString("sign"));
                                    mTokenParam.setP17_product(jsonObject1.getString("productName"));
                                    if (null != mPayParametercCallback) {
                                        mPayParametercCallback.payParameter(mTokenParam);
                                    }
                                }
                            } else {
                                Log.d(TAG, "Merchants configuration errors" + jsonObject.toString());
                                if (null != mPayParametercCallback) {
                                    mPayParametercCallback.failureParameter(context.getString(R.string.merchants_configuration_errors));
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.d(TAG, "get Merchants configuration errors" + e.toString());
                            if (null != mPayParametercCallback) {
                                mPayParametercCallback.failureParameter(context.getString(R.string.gain_merchants_configuration_errors));
                            }
                        }
                    }
                }
            }
        });
    }

    public void getPaySign(final Context context, String money, String typeId, String ordernumber, String ordertime) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("money", money);
            jsonObject.put("productTypeCode", typeId);
            jsonObject.put("typeCode", PAY_PARAM);
            jsonObject.put("orderCode", ordernumber);
            jsonObject.put("orderTime", ordertime);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d(TAG, "Merchants configuration errors" + e.toString());
            if (mPaySignCallback != null) {
                mPaySignCallback.failureSign(context.getString(R.string.merchants_configuration_errors));
            }
        }
        String url = getUrl(jsonObject.toString(), API_PAYPARAM);
        Log.d(TAG, "pay configuration  url = " + url);
        getCall(TAG, url, new PayCallback() {
            @Override
            public void onFailure() {
                if (null != mPaySignCallback) {
                    mPaySignCallback.failureSign(context.getString(R.string.merchants_configuration_errors));
                }
                Log.d(TAG, "Merchants pay configuration errors");
            }

            @Override
            public void onSuccess(Call call, Response response) throws IOException {
                if (null != response.body().toString()) {
                    String result = response.body().string();
                    if (response.isSuccessful()) {
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String flag = jsonObject.getString("flag");
                            if ("1".equals(flag)) {
                                String msg = jsonObject.getString("msg");
                                String str = getDecrypt(msg);
                                if (!TextUtils.isEmpty(str)) {
                                    JSONObject jsonObject1 = new JSONObject(str);
                                    mTokenParam.setP8_sign(jsonObject1.getString("sign"));
                                    if (null != mPaySignCallback) {
                                        mPaySignCallback.paySign(mTokenParam);
                                    }
                                }
                            } else {
                                Log.d(TAG, "pay configuration errors" + jsonObject.toString());
                                if (null != mPaySignCallback) {
                                    mPaySignCallback.failureSign(context.getString(R.string.merchants_configuration_errors));
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.d(TAG, "get Merchants pay configuration errors" + e.toString());
                            if (null != mPaySignCallback) {
                                mPaySignCallback.failureSign(context.getString(R.string.gain_merchants_configuration_errors));
                            }
                        }
                    }
                }
            }
        });
    }

    private String getUrl(String str, String api) {
        byte[] encode = PayAESUtil.encrypt(str, KEY_AES, VECTOR_AES);
        String dest = Base64.encodeToString(encode, Base64.DEFAULT);
        String replace = dest.replace("+", "-").replace("/", "_").replace("=", "~").replace("\r", "").replace("\n", "");
        String url = api + "/" + replace;
        return url;
    }

    private String getDecrypt(String msg) {
        String str = "";
        msg = msg.replace("-", "+").replace("_", "/").replace("~", "=");
        byte[] decryptFrom = Base64.decode(msg, Base64.DEFAULT);
        byte[] decryptResult = PayAESUtil.decrypt(decryptFrom, KEY_AES, VECTOR_AES);
        try {
            str = new String(decryptResult, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }


    void getCall(final String tag, String url, final PayCallback callback) {
        mOkHttpClient.newCall(new Request.Builder().url(url).build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (null != callback) {
                    callback.onFailure();
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (null != callback) {
                    callback.onSuccess(call, response);
                }
                if (null != response.body()) {
                    if (!response.isSuccessful()) {
                        Log.d(tag, " response body = null");
                    }
                } else {
                    Log.d(tag, " onResponse failure");
                }
            }
        });
    }

    public void setPayParameterListener(PayParametercCallback payParametercCallback) {
        mPayParametercCallback = payParametercCallback;
    }

    public void setPaySignListener(PaySignCallback paySignCallback) {
        mPaySignCallback = paySignCallback;
    }

    public interface PayParametercCallback {
        void payParameter(TokenParam tokenParam);

        void failureParameter(String str);
    }

    public interface PaySignCallback {
        void paySign(TokenParam tokenParam);

        void failureSign(String str);
    }

    public interface PayCallback {
        void onFailure();

        void onSuccess(Call call, Response response) throws IOException;
    }


}

